package cn.yunhe.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

import java.util.List;



@WebServlet("/UploadImgServlet")
public class UploadImgServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory diskFileItemFactory = null;
        ServletFileUpload servletFileUpload = null;
        if(servletFileUpload.isMultipartContent(request)){
            try {
                diskFileItemFactory = new DiskFileItemFactory();
                servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                servletFileUpload.setSizeMax(10*1024*1024);
                servletFileUpload.setHeaderEncoding("UTF_8");
                List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
                if(fileItemList!=null){
                    for (FileItem fileItem:fileItemList){
                        if(fileItem.isFormField()){
                           if("userName".equals(fileItem.getFieldName())){
                                String userName = fileItem.getString("utf-8");
                               System.out.println(userName);
                           }

                        }else{
                            String fileName = fileItem.getName();
                            String realpath = request.getSession().getServletContext().getRealPath("/img");
                            int index = realpath.lastIndexOf("img");
                            String path = realpath.substring(index)+"/"+fileName;
                            System.out.println(fileName);
                            System.out.println(path);
                            System.out.println("-------------"+realpath+"--------------");
                            File file = new File(realpath,fileName);
                         /*   fileItem.write(file);*/
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


































